let iapChannel = null;
import { getComboList } from '@/api/my.js';
import { httpTokenRequest } from '@/utils/http.js';
export default {
	data() {
		return {
			userInfo: {},
			showGz: false,
			setMealList: [],//套餐列表
			setMealIndex: 0,//选中套餐下标
			payNum: '',//充值数量
			maxNum: 10000, //最大
			minNum: 1, //最小
			//苹果支付
			taocanIndex: -1,
			toacanList: [],
			isRead: true,
			payType: 1,
			productIds: [],
		};
	},
	onLoad(e) {
		this.userInfo = uni.getStorageSync("userInfo");
		this.getSetMealList();
	},
	methods: {
		// 获取支付套餐
		getSetMealList() {
			getComboList().then(({ data, code, msg }) => {
				if (code == 1) {
					this.setMealList = data
					if (this.setMealList.length > 0) {
						this.setMealIndex = 0;
						this.setMealList.forEach(item => {
							this.productIds.push(item.ios_id)
						})
						this.chooseMeal(this.setMealList[0], 0);
						//检查苹果支付渠道
						// #ifdef APP-PLUS
						this.checkAppleChannel()
						// #endif
					} else {
						this.$used.appBack(msg)
					}
				}
			})
		},
		//选择套餐
		chooseMeal(item, index) {
			this.setMealIndex = index;
			this.payNum = item.amount;
		},

		/**
	 * checkAppleChannel - 检查苹果支付渠道。
	 *
	 * 此函数检查是否存在“appleiap”支付渠道。
	 * 如果渠道存在，它将隐藏加载动画并调用`requestOrder`函数。
	 * 如果渠道不存在，它将隐藏加载动画并调用带有参数'1'的`errorMsg`函数。
	 *
	 * @return {undefined} 此函数不返回任何值。
	 */
		checkAppleChannel() {
			uni.showLoading({ title: '支付渠道检查...', mask: true });
			plus.payment.getChannels((channels) => {
				console.log("获取到channel" + JSON.stringify(channels));
				iapChannel = channels.find(channel => channel.id === 'appleiap');
				if (iapChannel) {
					// console.log("检测到苹果支付渠道");
					// #ifdef APP-PLUS
					this.requestOrder();
					// #endif
				} else {
					this.errorMsg('1');
				}
			}, () => {
				this.errorMsg('2');
			}).finally(() => {
				uni.hideLoading();
			});
		},

		/**
 * requestOrder - 检测支付环境
 */
		requestOrder() {
			uni.showLoading({
				title: '检测支付环境...',
				mask: true
			})
			iapChannel.requestOrder(this.productIds, (orderList) => {
				uni.hideLoading()
			}, (e) => {
				console.log('检测支付环境')
				console.log(this.productIds)
				console.log('requestOrder failed: ' + JSON.stringify(e))
				uni.hideLoading()
				this.errorMsg('6')
			})
		},
		//调起支付，通知后台
		payClick() {
			uni.showLoading({
				title: '调起支付中...',
				mask: true
			})
			httpTokenRequest({
				method: 'POST',
				url: `/api/Iospay/place`,
				params: {
					id: this.setMealList[this.setMealIndex].id,
				}
			}).then(res => {
				console.log("充值下单结果Iospay/place", res);
				if (res.code == 1) {
					this.startPayment(res.data.order_sn); //发起支付动作
				} else {
					uni.hideLoading();
					this.$tools.showToast(res.msg);
				}
			})
				.catch(err => {
					uni.hideLoading();
					console.log('错误回调', err);
				});
		},


		//开始支付
		startPayment(payOrder) {
			uni.showLoading({
				title: '支付中...',
				mask: true
			})

			uni.requestPayment({
				provider: 'appleiap',
				orderInfo: {
					productid: this.productIds[this.setMealIndex]
				},
				success: (e) => {
					console.log('支付完成success')
					uni.hideLoading();
					const data = {
						receipt: e.transactionReceipt,
						order_no: payOrder
					}

					httpTokenRequest({
						method: 'POST',
						url: this.$paths.iosPays,
						params: data
					})
						.then(res => {
							console.log(res)
							if (res.code === 1) {
								console.log("充值下单结果", res);
								this.$tools.showToast("购买成功");
								this.getSetMealList();
							} else {
								this.$tools.showToast('充值下单失败');
							}
						})
						.catch(err => {
							uni.hideLoading();
							console.log('错误回调', err);
						});
				},
				fail: (e) => {
					uni.hideLoading();
					console.log('fail')
					uni.showModal({
						content: "取消支付",
						showCancel: false
					})
				}
			})
		},

		//超时提示
		errorMsg(e) {
			uni.showModal({
				content: "请求超时，请稍后重试",
				showCancel: false
			})
		},
	}
}